package chances.system.operator.repo;

import static org.springframework.data.jpa.repository.query.QueryUtils.toOrders;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;

import chances.system.operator.entity.EnumData;

/**
* @author panzx
* @version 创建时间：2017年9月14日 下午3:36:49
*/
public class EnumDataRepositoryImpl {
    @PersistenceUnit
    private EntityManagerFactory emf;

    public Page<EnumData> filter(@Param("parentId") Long parentId, Pageable pageable) {

        EntityManager em = emf.createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<EnumData> cq = cb.createQuery(EnumData.class);
        Root<EnumData> root = cq.from(EnumData.class);
        Path<String> sqlParentId = root.get("parentId");

        List<Predicate> predicates = new ArrayList<Predicate>();
        if (parentId != null) {
            predicates.add(cb.equal(sqlParentId, parentId));
        } else {
            predicates.add(cb.isNull(sqlParentId));
        }
        if (predicates.size() > 0) {
            Predicate[] predicatesArr = predicates.toArray(new Predicate[predicates.size()]);
            cq = cq.where(cb.and(predicatesArr));
        }
        cq = cq.orderBy(toOrders(pageable.getSort(), root, cb));

        List<EnumData> sql_count = em.createQuery(cq).getResultList();

        List<EnumData> sql_list = em.createQuery(cq)
                .setFirstResult(pageable.getPageNumber() * pageable.getPageSize())
                .setMaxResults(pageable.getPageSize()).getResultList();
        em.close();

        Page<EnumData> pageImpl = new PageImpl<EnumData>(sql_list, pageable, sql_count.size());
        return pageImpl;
    }
}
